package com.sky.controller.admin;

import com.sky.constant.MessageConstant;
import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.UUID;

/**
 * @BelongsProject: sky-take-out
 * @BelongsPackage: com.sky.controller.admin
 * @Author: song
 * @CreateTime: 2023-12-27  14:52
 * @Description: Alioss文件上传
 * @Version: 1.0
 */
@RestController
@RequestMapping("/admin/common")
@Api(tags = "通用接口")
@Slf4j
public class CommonController {
    @Value("${file.path}")
    private String dirPath;
    private AliOssUtil aliOssUtil;

    /*
     * @description:文件上传
     * @author: song
     * @date: 2023/12/27 15:23
     * @param: [file]
     * @return: com.sky.result.Result<java.lang.String>
     **/
    @PostMapping("/upload")
    @ApiOperation("文件上传")
    public Result<String> upload(MultipartFile file){
        log.info("文件上传：{}",file);
        try {
            InputStream inputStream = file.getInputStream();
            // 原始文件名
            String originalFilename = file.getOriginalFilename();
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            // 构建新文件名称。
            String objectName = UUID.randomUUID().toString() + extension;
            //String filePath = aliOssUtil.upload(file.getBytes(), objectName);
            Files.copy(inputStream,new File(dirPath + objectName).toPath(),
                    StandardCopyOption.REPLACE_EXISTING);
            //拼接上传文件路径
            String replaceAll ="D:/cangqiong/pictrue/";
            String filepath = ServletUriComponentsBuilder.fromCurrentContextPath()
                    .path(replaceAll)
                    .path(objectName)
                    .toUriString();
            return Result.success(filepath);
        } catch (IOException e) {
            log.error("文件上传失败：{}",e);
        }
        return Result.error(MessageConstant.UPLOAD_FAILED);
    }
}
